<%@ include file="/WEB-INF/views/commonJSTL.jsp" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>${s_UserPharmacy.pharmacy.name}</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<%@ include file="/WEB-INF/views/commonResources.jsp" %>
<script src="<c:url value="/resources/js/jquery.maxlength.min.js" />"></script>
<c:set var="showTypeComposition" scope="page"><fmt:message key="show.form.selected.typeComposition"/>.</c:set>
<c:set var="showQuantity" scope="page"><fmt:message key="show.form.quantity"/>.</c:set>		
  <style>
	.custom-combobox {
		position: relative;
		display: inline-block;
	}
	.custom-combobox-toggle {
		position: absolute;
		top: 0;
		bottom: 0;
		margin-left: -1px;
		padding: 0;
		/* support: IE7 */
	
	}
	.custom-combobox-input {
		margin: 0;
		padding: 0.3em;
	}
	
	.ui-autocomplete {
	    max-height: 100px;
	    overflow-y: auto;   /* prevent horizontal scrollbar */
	    overflow-x: hidden; /* add padding to account for vertical scrollbar */
	}
</style>
<script type="text/javascript">
(function( $ ) {
	$.widget( "custom.combobox", {
		_create: function() {
			this.wrapper = $( "<span>" ).addClass( "custom-combobox" ).insertAfter( this.element );
			this.element.hide();
			this._createAutocomplete();
			this._createShowAllButton();
		},
		_createAutocomplete: function() {
			var selected = this.element.children( ":selected" ),
			value = selected.val() ? selected.text() : "";
			this.input = $( "<input>" ).appendTo( this.wrapper ).val( value ).attr( "title", "" )
			.addClass( "custom-combobox-input ui-widget ui-corner-left" )
			.autocomplete({
				delay: 0,
				minLength: 0,
				source: $.proxy( this, "_source" )
			}).tooltip({
				tooltipClass: "ui-state-highlight"
			});
			this._on( this.input, {
				autocompleteselect: function( event, ui ) {
					ui.item.option.selected = true;
					this._trigger( "select", event, {item: ui.item.option});
				},autocompletechange: "_removeIfInvalid"
			});
		},
		_createShowAllButton: function() {
			var input = this.input,wasOpen = false;
			$( "<a>" ).attr( "tabIndex", -1 ).attr( "title", "Show All Items" ).tooltip().appendTo( this.wrapper ).button({
				icons: {primary: "ui-icon-triangle-1-s"},text: false
			}).removeClass( "ui-corner-all" ).addClass( "custom-combobox-toggle ui-corner-right" ).mousedown(function() {
				wasOpen = input.autocomplete( "widget" ).is( ":visible" );
			}).click(function() {
				input.focus();
				// Close if already visible
				if ( wasOpen ) {
					return;
				}
				// Pass empty string as value to search for, displaying all results
				input.autocomplete( "search", "" );
			});
		},
		_source: function( request, response ) {
			var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
			response( this.element.children( "option" ).map(function() {
					var text = $( this ).text();
					if ( this.value && ( !request.term || matcher.test(text) ) )
					return {
						label: text,
						value: text,
						option: this
					};
				}) 
			);
		},
		_removeIfInvalid: function( event, ui ) {
			// Selected an item, nothing to do
			if ( ui.item ) {
				return;
			}
			// Search for a match (case-insensitive)
			var value = this.input.val(),
			valueLowerCase = value.toLowerCase(),
			valid = false;
			this.element.children( "option" ).each(function() {
				if ( $( this ).text().toLowerCase() === valueLowerCase ) {
					this.selected = valid = true;
					return false;
				}
			});
			// Found a match, nothing to do
			if ( valid ) {
				return;
			}
			// Remove invalid value
			this.input.val( "" ).attr( "title", value + " didn't match any item" ).tooltip( "open" );
			this.element.val( "" );
			this._delay(function() {
				this.input.tooltip( "close" ).attr( "title", "" );
			}, 2500 );
			this.input.data( "ui-autocomplete" ).term = "";
		},
		_destroy: function() {
			this.wrapper.remove();
			this.element.show();
		}
	});
})( jQuery );

	var listTypeCompositions = [];
	var typesCompValuesIni = [];
	var quantityValue = 0;
	var indexRow = 0;
	var currentIndexRow = -1;
	var listAutoCompletGenericValue = [];
	
	<c:forEach var="item" items="${listTypeComposition}">
		var typeComposition = {typeCompositionId:"<c:out value="${item.typeCompositionId}"/>",name:"<c:out value="${item.name}"/>"};
		listTypeCompositions.push(typeComposition);
	</c:forEach>	
	<c:forEach var="item" items="${listGenericValue}">
		var genericValue = {genericValueId:"<c:out value="${item.genericValueId}"/>",pharmacyId:"<c:out value="${item.pharmacyId}"/>"
				,group:"<c:out value="${item.group}"/>",description:"<c:out value="${item.description}"/>"
				,initials:"<c:out value="${item.initials}"/>",order:"<c:out value="${item.order}"/>"};
		listAutoCompletGenericValue.push(genericValue.description);
	</c:forEach>
	
	$(document).ready(function(){		
		$( "#genericName" ).combobox();
		
		$(".addNewProvider").click(function(){
			$("#dialogNewProvider").load( "formNewProvider",function(){
				openDialogModalForm("#dialogNewProvider","Nuevo Proveedor",null);
			});
		});
		
		$("#dialogNewProvider").dialog({autoOpen: false, height: 480, width: 700, modal: true,
			buttons: {
	            "Aceptar": function() {
	            	var flag = $("#formProvider").valid();
	                if(flag){	                	
		            	$.ajax({ 
		            		type: "POST",
		            		url: 'formNewProvider',
			           	   	dataType: "json",			        		
                            data: $('#formProvider').serialize(),
			           	    success:function(provider){
			           	    	var element = $("#productPKproviderId");
	    			        	element.empty().append("<option value=''>Seleccione</option>");
	    			        	
	    			        	if(provider.providers[0].name != ''){
	    			        		for(var i=0; i<provider.providers.length; i++){
	    			        			var obj = provider.providers[i];
	    			        			var selec = '';
	    			        			if(obj.providerId == provider.id)
	       			                    	selec='selected="selected"';
	    			        			element.append("<option value='"+obj.providerId+"' "+selec+">"+obj.name+"</option>");
	    			        		}
	    			        	}			          	    	
			           	    	$("#dialogNewProvider").dialog( "close" );
			           	    	
			           		}, 
			           		error: 	function(){alert('Error en request..');} }); 
	                	
	            	}
	            },
	            Cancelar: function() { $( this ).dialog( "close" );}
			},
			close: function(){ $( this ).dialog( "close" ); }
		});
		
		$(".buttonSave").click(function(){
			var flag = $("#formGrupo").valid();
			if(flag){
				var boolActiveName = false;				
				if($("#genericName").val() != ''){
					$("#requiredGenericName").toggleClass("noDisplay",true);
					boolActiveName=true;
				}else
					$("#requiredGenericName").toggleClass("noDisplay",false);
					
				
				if( boolActiveName && $("#typeCompositionsTable tbody tr").hasClass("tr_decorado") && $("#productAttributeTable tbody tr").hasClass("tr_decorado")){
					$("#formGrupo").submit();	
				}else{
					if(!$("#typeCompositionsTable tbody tr").hasClass("tr_decorado"))
						$("#requiredComp").toggleClass("noDisplay",false);
					
					if(!$("#productAttributeTable tbody tr").hasClass("tr_decorado"))
						$("#requiredproductAttribute").toggleClass("noDisplay",false);
				}
			}
		});
		
		$("#dialogo").dialog({autoOpen: false, height: 400, width: 680, modal: true,
			open: function(event, ui){
				if(quantityValue == 0){
					$("input:radio[name=quantity]:checked").change();
					$("input:radio[name=quantity]").prop("disabled",false);
				}else{
					$("#quantity"+quantityValue).prop("checked", true);
					$("input:radio[name=quantity]:checked").change();
					for (var i = 0; i < typesCompValuesIni.length; i++) {
						$("#typeCompositionIdDialog_"+i).val(typesCompValuesIni[i]);
						$("#typeCompositionIdDialog_"+i).prop("disabled",true);
					}
					$("input:radio[name=quantity]").prop("disabled",true);
				}
			},
			buttons: {
	            "Aceptar": function() {
	            	var flag = $("#formDialog").valid();
	                if(flag){
	                	var quantity = parseInt($("input:radio[name=quantity]:checked").val(),10);
	                	var name = $("#nameComposition").val();
	                	addEditTable(quantity,name);
	                	$(this).dialog("close");
	                } 
	            },
	            Cancelar: function() {
	                $( this ).dialog( "close" );
	            }
			},
			close: function() {
				$( this ).dialog( "close" );
			}
		});
		
		$("#buttonAddComp").click(function(){
			$("#isPopUpEdite").val("false");
			openDialogModalForm("#dialogo","Nueva Composición",null);
		});
		
		$("#dialogoProductAttribute").dialog({autoOpen: false, height: 400, width: 680, modal: true,
			buttons: {
	            "Aceptar": function() {
	            	var flag = $("#formDialogProductAttribute").valid();
	                if(flag){
	            		addEditTableProductAttribute();
	                	$(this).dialog("close");
	                } 
	            },
	            Cancelar: function() {
	                $( this ).dialog( "close" );
	            }
			},
			close: function() {
				$( this ).dialog( "close" );
			}
		});
		
		$("#buttonAddProductAttri").click(function(){
			openDialogModalForm("#dialogoProductAttribute","Nuevo Producto Attributo",null); // parameters (identifier element, title form, function call back)
		});
		
		
		
		/****************************** STARD FUNCTIONS DIALOG *******************************/
		$("input:radio[name=quantity]").change(function(){
			var quantity = parseInt($(this).val(),10);
			$("#valueRadio").val(quantity);
			var html = "";
			for (var i = 0; i < quantity; i++) {
				"<c:set var='showTypeComposition' scope='page'><fmt:message key='show.form.selected.typeComposition'/></c:set>";
				html += "<div style='clear:both;'>"+	
					   "	<label class='form_align45' for='typeCompositionIdDialog_"+i+"'><fmt:message key='form.typeComposition'/> "+(i+1)+" :</label>"+
					   "	<select name='typeCompositionIdDialog_"+i+"' id='typeCompositionIdDialog_"+i+"' class='required form_input_align' title='${showTypeComposition} "+(i+1)+" .'>"+
					   "		<option value=''><fmt:message key='form.selected'/></option>";
					for (var j = 0; j < listTypeCompositions.length; j++) {
						var obj = listTypeCompositions[j];
						html += "<option value='"+obj.typeCompositionId+"' >"+obj.name+"</option>";
					}
				html += "	</select>"+
						"	<label class='error'>*</label>"+
						"</div>";

				"<c:set var='showQuantity' scope='page'><fmt:message key='show.form.quantity'/></c:set>";
				html += "<div style='clear:both;'>"+
						"	<label class='form_align45'><fmt:message key='form.quantity'/> "+(i+1)+" :</label>"+
						"	<input type='text' name='quantity_"+i+"' id='quantity_"+i+"' placeholder='texto' class='required form_input_align' title='${showQuantity} "+(i+1)+" .'/>"+
						"	<label class='error'>*</label>"+
						"</div>";
				html += "";
				
				"<c:set var='showCheckHealth' scope='page'><fmt:message key='show.form.checkHealth'/></c:set>";
				html += "<div style='clear:both;'>"+
						"	<label class='form_align45'><fmt:message key='form.checkHealth'/> "+(i+1)+" :</label>"+
						"	<input type='text' name='checkHealth_"+i+"' placeholder='texto'  id='checkHealth_"+i+"' class='form_input_align' title='${showCheckHealth} "+(i+1)+" .'/>"+
						"</div>";
				html += "";
			}
			$("#dynamicsFields").html(html);
		}); 
		
		// this event is to delete a row of a table. 
		$('#typeCompositionsTable').on('click', '.deleteRowCarga', function () {
			$(this).parents('tr').first().remove();
			/* when we delete we have to verify that not exist a row because if exist we have to reset the array 'typesCompValuesIni' */
			if(!$("#typeCompositionsTable tbody tr").hasClass("tr_decorado")){
				$('#typeCompositionsTable thead tr').remove();
				typesCompValuesIni = [];
				quantityValue = 0;
			}
		});
		
		
		$('#productAttributeTable').on('click', '.deleteRowCarga', function () {
			$(this).parents('tr').first().remove();
			/* when we delete we have to verify that not exist a row because if exist we have to reset the array 'typesCompValuesIni' */
			if(!$("#productAttributeTable tbody tr").hasClass("tr_decorado")){
				$('#productAttributeTable thead tr').remove();
			}
		});
		
		// autocomplete
		$( "#nameProductAttribute" ).autocomplete({
			 source: listAutoCompletGenericValue,delay: 10
		});
		// complete carateres on maxLength
        $('div.maxLength textarea').maxlength({max:1000,slider: true});

		
		/****************************** END FUNCTIONS DIALOG   *******************************/
		
      //permit only numbers
		$('.numberOnlyNumber').keyup(function () {
	         if (this.value != this.value.replace(/[^0-9]/g,'')) {
	            this.value = this.value.replace(/[^0-9]/g, '');
	         }
	     });
		
		//permit only text
		$('.lettersOnly').keyup(function () {
	         if (this.value != this.value.replace(/[^A-Za-z\s]/g, '')) {
	            this.value = this.value.replace(/[^A-Za-z\s]/g, '');
	         }
	     });
	}); // END READY
	
	// FUNCTION EDIT PRODUCT ATTRIBUTE
	function editProductAttribute(indexRow){
		currentIndexRow = indexRow;
		$("#isPopUpEditeProductAttribute").val("true");
		openDialogModalForm("#dialogoProductAttribute","Editar Producto Attributo",function(){
			$("#nameProductAttribute").val($("#productAttributeTable tbody #nameTD"+indexRow).text());
			$("#detailProductAttribute").val($("#productAttributeTable tbody #detailTD"+indexRow).text());
			$("#orderProductAttribute").val($("#productAttributeTable tbody #orderTD"+indexRow).text());
		});
	}	
	
	function addEditTableProductAttribute(){
		var textHtml = "";
		var isPopUpEdit = ($("#isPopUpEditeProductAttribute").val() == "true");
		$("#requiredproductAttribute").toggleClass("noDisplay",true);
		if(!$("#productAttributeTable tbody tr").hasClass("tr_decorado")){
			textHtml = 	"<tr>"+
						"	<th class='th_decoradoRowspan'><fmt:message key='table.order'/></th>"+
						"	<th class='th_decoradoRowspan'><fmt:message key='table.name'/></th>"+
						"	<th class='th_decoradoRowspan'><fmt:message key='table.description'/></th>"+
						"	<th class='th_decoradoRowspan' colspan='2'><fmt:message key='table.actions'/></th>"+
						"</tr>";
			$("#productAttributeTable thead").append(textHtml);
		}
		if(!isPopUpEdit){ // add new row
			var value = $("#nameProductAttribute").val()+"&&"+$("#detailProductAttribute").val()+"&&"+$("#orderProductAttribute").val();
			textHtml = "";
			textHtml += "<tr class='tr_decorado'>"+
						"	<td class='td_decorado' id='orderTD"+indexRow+"'>"+$("#orderProductAttribute").val()+"</td>"+
						"	<td class='td_decorado' id='nameTD"+indexRow+"'>"+$("#nameProductAttribute").val()+"</td>"+
						"	<td class='td_decorado' id='detailTD"+indexRow+"'>"+$("#detailProductAttribute").val()+"</td>"+
						"	<td class='td_decorado' style='text-align: right'><div class='botonEditar test'><a href='javascript:editProductAttribute("+(indexRow)+")' title='Pulsa aqu&iacute; para Editar'></a></div></td>"+
	        			"	<td class='td_decorado' style='text-align: right'><div class='botonEliminar'><a href='#' class='deleteRowCarga' title='Pulsa aqu&iacute; para Eliminar'></a></div></td>"+
	        			"	<input type='hidden' name='productAttributeValues' id='productAttributeValues_"+indexRow+"' value='"+value+"' />";
			textHtml += "</tr>";		
			$("#productAttributeTable tbody").append(textHtml);
			indexRow++;
		}else{
			var value = $("#nameProductAttribute").val()+"&&"+$("#detailProductAttribute").val()+"&&"+$("#orderProductAttribute").val();
			$("#productAttributeTable tbody #nameTD"+currentIndexRow).text($("#nameProductAttribute").val());
			$("#productAttributeTable tbody #detailTD"+currentIndexRow).text($("#detailProductAttribute").val());
			$("#productAttributeTable tbody #orderTD"+currentIndexRow).text($("#orderProductAttribute").val());
			$("#productAttributeValues_"+currentIndexRow).val(value);
			$("#isPopUpEditeProductAttribute").val("false");
		}
	}
	
	function editComposition(indexRow){
		$("#isPopUpEdite").val("true");
		currentIndexRow = indexRow;
		var values = $("#compositionValue_"+currentIndexRow).val();
		openDialogModalForm("#dialogo","Editar Composición",function(){
			var firstArrayValues = values.split("||");
			$("#nameComposition").val(firstArrayValues[0]);
			var compTypeArray = firstArrayValues[1].split("|**|");
			for (var i = 0; i < compTypeArray.length; i++) {
				var compTypeArrayInto = compTypeArray[i].split("&&");
				$("#quantity_"+i).val(compTypeArrayInto[1]); 
				if(compTypeArrayInto[2] != '')
					$("#checkHealth_"+i).val(compTypeArrayInto[2]); 
			}		
		});
	}	
	
	function addEditTable(quantity,name){		
		var textHtml = "";
		var textValue = "";
		var isPopUpEdite = ($("#isPopUpEdite").val() == "true");
		$("#requiredComp").toggleClass("noDisplay",true);
		if(!$("#typeCompositionsTable tbody tr").hasClass("tr_decorado")){
			quantityValue = quantity;
			textHtml = "<tr><th class='th_decoradoRowspan' ><fmt:message key='table.composition'/></th>";
			for (var i = 0; i < quantity; i++) {
				var typeComposition = $("#typeCompositionIdDialog_"+i+" option:selected").text();
				textHtml += "<th class='th_decoradoRowspan'>"+typeComposition.toUpperCase()+"</th>";
				textHtml += "<th class='th_decoradoRowspan'>REGISTRO SANITARIO</th>";
				typesCompValuesIni.push($("#typeCompositionIdDialog_"+i+" option:selected").val());
			}
			textHtml += "<th class='th_decoradoRowspan' colspan='2'><fmt:message key='table.actions'/></th>";
			textHtml += "</tr>";
			$("#typeCompositionsTable thead").append(textHtml);
		}
		if(!isPopUpEdite){ // add new row
			textHtml = "";
			textHtml += "<tr class='tr_decorado'> <td id='nameCompTD_"+indexRow+"' class='td_decorado'>"+name+"</td>";
			textValue = name+"||";
			for (var i = 0; i < quantity; i++) {
				var value = $("#typeCompositionIdDialog_"+i+" option:selected").val()+"&&"+$("#quantity_"+i).val();
				if($("#checkHealth_"+i).val() != '')
					value += "&&"+$("#checkHealth_"+i).val();
				textHtml += "<td id='quantityValueTD_"+indexRow+"_"+i+"' class='td_decorado'>"+$("#quantity_"+i).val()+"</td>";
				
				var cheHealt='';
				if($("#checkHealth_"+i).val() != '')
					cheHealt = $("#checkHealth_"+i).val();
				textHtml += "<td id='chechHealtValueTD_"+indexRow+"_"+i+"' class='td_decorado'>"+cheHealt+"</td>";
				if(i == 0){
					textValue += value;
				}else{
					textValue += "|**|"+value;
				}
			}
			textHtml += "	<td class='td_decorado' style='text-align: right'><div class='botonEditar test'><a href='javascript:editComposition("+indexRow+")' title='Pulsa aqu&iacute; para Editar'></a></div></td>"+
	        			"	<td class='td_decorado' style='text-align: right'><div class='botonEliminar'><a href='#' class='deleteRowCarga' title='Pulsa aqu&iacute; para Eliminar'></a></div></td>"+
	        			"	<input type='hidden' name='compositionsValues' id='compositionValue_"+indexRow+"' value='"+textValue+"' />";
			textHtml += "</tr>";
			$("#typeCompositionsTable tbody").append(textHtml);
			indexRow++;
		}else{ // edit a row
			$("#typeCompositionsTable tbody #nameCompTD_"+currentIndexRow).text(name);
			textValue = name+"||";
			for (var i = 0; i < quantity; i++) {
				var value = $("#typeCompositionIdDialog_"+i+" option:selected").val()+"&&"+$("#quantity_"+i).val();
				if($("#checkHealth_"+i).val() != '')
					value += "&&"+$("#checkHealth_"+i).val();
				$("#typeCompositionsTable tbody #quantityValueTD_"+currentIndexRow+"_"+i).text($("#quantity_"+i).val());
				var cheHealt='';
				if($("#checkHealth_"+i).val() != '')
					cheHealt = $("#checkHealth_"+i).val();
				$("#typeCompositionsTable tbody #chechHealtValueTD_"+currentIndexRow+"_"+i).text(cheHealt);
				if(i == 0){
					textValue += value;
				}else{
					textValue += "|**|"+value;
				}
			}
			$("#compositionValue_"+currentIndexRow).val(textValue);
			$("#isPopUpEdite").val("false");
		}
	}

	function mainProducts(){
		location.href = "products?_menuId=1&_subMenuId=1&_optionId=3";
	}
	
</script>
</head>

<body>
<div id="top-wrap">
	<%@include file="../../../head.jsp"  %>
	<div id="bodySpace">
		
	    <div class="clearfix" id="middle" style="position: absolute">  <!-- aqui va la ruta -->
	        <!-- aqui va el arbol de entrada -->
	        <div id="breadcrumb">
	            <ul>
                    <li><a href="<spring:url value="/mainFront?" htmlEscape="true" />">Home</a></li>	
                    <li><span style="color:#666"><fmt:message key="title.configuration"/></span></li>		
                    <li><span style="color:#666"><fmt:message key="title.activePrincipleProducts"/></span></li>		
                    <li class="current-page"><span class="end"><span class="middle"><fmt:message key="title.products"/></span></span></li>
                </ul>
	        </div>
	    </div>
	    
	    <div id="principal">
            <!-- izquierda -->
            <div class="cuerpo2y" style="border: 0px solid"><br/><br/><!-- estos break son necesarios ya q uso absolute en css  cuerpo izquierdo-->
                <div class="izq">
					<%@include file="../../../bodyIzq.jsp" %>	
                </div>
                <h2 class="decorado">
                	<c:choose>		
						<c:when test="${param._productId == null && param._providerId == null}">
							<fmt:message key="show.register"/> <fmt:message key="title.product"/>
						</c:when>
						<c:otherwise>
							<fmt:message key="show.modify"/> <fmt:message key="title.product"/>
						</c:otherwise>
					</c:choose>	
                </h2>&nbsp;</br></br> 
                <div class="medio" style="border: 0px solid">
					<div id="imgLoad" style="float: left;width: 100%;display: none;"><img src="<c:url value="/resources/images/imgLoad/ajax-loader.gif" />" width="32" height="32" alt="ajax-loader.gif" style="position:absolute; top:30%; left:50%;"/></div> 
					<div id="products">



<div id="dialogoTipoAlert">
	<div id="dialogoText"></div>
</div>					

<div id="dialogNewProvider"></div> <!-- This is to new provider -->

<div id="dialogo">
<form id="formDialog">
	<input type="hidden" name="isPopUpEdite" id="isPopUpEdite" value="false" />		
	<div style="clear:both;">
		<c:set var="showName" scope="page"><fmt:message key="show.form.name"/>.</c:set>		
		<label class="form_align45"><fmt:message key="form.name"/> :</label>
		<input type="text" name="nameComposition" id="nameComposition" value="" class="required form_input_align lettersOnly" title="${showName}" placeholder="letras"/>
		<label class="error">*</label>
	</div>
	<div style="clear:both;">
		<label class="form_align45"><fmt:message key="form.quantityTypeComposition"/> :</label>
		<input type="radio" name="quantity" id="quantity1" value="1" checked="checked" /><label for="quantity1">&nbsp;1&nbsp;&nbsp;</label>
		<input type="radio" name="quantity" id="quantity2" value="2" /><label for="quantity2">&nbsp;2&nbsp;&nbsp;</label>
		<input type="radio" name="quantity" id="quantity3" value="3" /><label for="quantity3">&nbsp;3&nbsp;&nbsp;</label>
		<input type="radio" name="quantity" id="quantity4" value="4" /><label for="quantity4">&nbsp;4&nbsp;&nbsp;</label>
	</div>				
	<div id="dynamicsFields">
	</div>		
</form>		
</div>

<div id="dialogoProductAttribute"><br/>
	<form id="formDialogProductAttribute">
		<input type="hidden" name="isPopUpEditeProductAttribute" id="isPopUpEditeProductAttribute" value="false" />
		<div style="clear:both;">
			<c:set var="showName" scope="page"><fmt:message key="show.form.name"/>.</c:set>		
			<label class="form_align45"><fmt:message key="form.name"/> :</label>
			<input type="text" name="nameProductAttribute" id="nameProductAttribute" value="" class="required form_input_align lettersOnly" title="${showName}" placeholder="letras"/>
			<label class="error">*</label>
		</div>
		<div style="clear:both;">
			<c:set var="showDetail" scope="page"><fmt:message key="show.form.detail"/>.</c:set>		
			<label class="form_align45"><fmt:message key="form.detail"/> :</label>
			<div class="maxLength">
	        	<textarea name="detailProductAttribute" id="detailProductAttribute" class="required form_input_align" rows="4" title="${showName}" placeholder="texto"></textarea>
	        </div>
			<label class="error">*</label>
		</div>	
		<div style="clear:both;">
			<c:set var="showOrder" scope="page"><fmt:message key="show.form.order"/>.</c:set>		
			<label class="form_align45"><fmt:message key="form.order"/> :</label>
			<input type="text" name="orderProductAttribute" id="orderProductAttribute" value="" maxlength="2" class="required form_input_align numberOnlyNumber" title="${showOrder}" placeholder="números"/>
			<label class="error">*</label>
		</div>		
	</form>
</div>
		
					
						<form:form method="post" id="formGrupo" commandName="product">   
							<form:hidden path="productPK.productId"/> 
							<form:hidden path="active"/> 
							<form:hidden path="provider.providerId"/> 						
							
							<input type="hidden" name="valueRadio" id="valueRadio"/>
							<input type="hidden" name="tempPharmacyId" id="tempPharmacyId" value="${s_UserPharmacy.pharmacy.pharmacyId}"/>

							<c:set var="laboratoryShow" scope="page"><fmt:message key="show.form.selected.laboratory"/>.</c:set>																																				                             												
							<div style="clear:both;">
								<label class="form_align43"><fmt:message key="form.laboratory"/> :</label>
								<form:select path="productPK.providerId" id="productPKproviderId" class="form_input_align required" title="${laboratoryShow}">		   			
									<option value="">Seleccione</option>
									<c:forEach var="item" items="${listProvider}">
										<form:option value="${item.providerId}"><c:out value="${item.name}"/></form:option>		            	
									</c:forEach>
								</form:select>								
								&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" class="boton addNewProvider" value="<fmt:message key="button.add"/> <fmt:message key="title.New"/> <fmt:message key="form.provider"/>" title='<fmt:message key="onclick.add"/> <fmt:message key="title.New"/> <fmt:message key="form.provider"/>.'/>
								<label class="error"><form:errors path="productPK.providerId" cssClass="error"></form:errors>*</label>
							</div>
							
							<c:set var="showCommercialName" scope="page"><fmt:message key="show.form.commercialName"/>.</c:set>																																				                             												
							<div style="clear:both;">
								<label class="form_align43"><fmt:message key="form.commercialName"/>:</label>
								<form:input path="name" id="name" class="required form_input_align" title="${showCommercialName}" placeholder="texto"/>
								<label class="error"><form:errors path="name" cssClass="error"></form:errors>*</label>
							</div>
							
							<div style="clear:both;">
								<label class="form_align43"><fmt:message key="form.activePrinciple"/>:</label>		
								<select name="genericName" id="genericName" class="form_input_align" >
									<option value=""><fmt:message key="form.selected"/></option>
									<c:forEach var="item" items="${listActiveSubstance}">
										<c:set var="selec" value="" />
										<c:if test="${item.name == product.genericName}">
											<c:set var="selec" value="selected='selected'" />
										</c:if>
										<option value="${item.activeSubstanceId}" ${selec}>${item.name}</option>
									</c:forEach>            							
								</select>	
								&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
								<label>(<fmt:message key="form.genericName"/>)</label>
								<label id="requiredGenericName" class="noDisplay requeredDataTable">Seleccione y despues presione registrar</label>
							</div>
							
							<br/>
							<c:set var="showGeneralIndication" scope="page"><fmt:message key="show.form.generalIndication"/>.</c:set>																																				                             												
							<div style="clear:both;">
								<label class="form_align43"><fmt:message key="form.generalIndication"/>:</label>
								<form:input path="generalIndication" id="generalIndication" class="required form_input_align lettersOnly" title="${showGeneralIndication}" placeholder="letras"/>
								<label class="error"><form:errors path="generalIndication" cssClass="error"></form:errors>*</label>
							</div>	
							
							<div style="clear:both;">
								<label class="form_align43"><fmt:message key="form.composition"/>:</label>
								&nbsp;&nbsp;<input type="button" id="buttonAddComp" class="boton" value="<fmt:message key="button.add"/> <fmt:message key="title.composition"/>" title='<fmt:message key="onclick.add"/> <fmt:message key="title.composition"/>.'/>
								<label class="error noComposition">*</label>
							</div>
														
							<div style="clear:both;">
   	                    		<label class="form_align43"></label>
   	                    		<div id="requiredComp" class="form_input_align noDisplay requeredDataTable" >Debe seleccionar al menos una composici&oacute;n <br/></div>
    	                    	<table id="typeCompositionsTable" class="tabla_decorado">
							     	<thead>
							     	<c:if test="${(not empty listProductAttributes)}" >
							     		<script type="text/javascript">
						     				quantityValue = "<c:out value="${tempValueQuantityRadio}"/>";
						     				$("#valueRadio").val(quantityValue);
						     			</script>
										<tr>
											<th class='th_decoradoRowspan' ><fmt:message key='table.composition'/></th>
								     		<c:forEach var="i" begin="0" end="${tempValueQuantityRadio-1}">
									     		<c:set var="name" value="${fn:toUpperCase(listComposition[i].typeCompositionId.name)}" />
												<th class='th_decoradoRowspan'>${name}</th>
												<th class='th_decoradoRowspan'>REGISTRO SANITARIO</th>
												<script type="text/javascript">
								    				typesCompValuesIni.push("<c:out value="${listComposition[i].typeCompositionId.typeCompositionId}"/>");
								     			</script>
											</c:forEach>
											<th class='th_decoradoRowspan' colspan='2'><fmt:message key='table.actions'/></th>
										</tr>
									</c:if>
							     	</thead>	
							     	<tbody>
										<c:if test="${(not empty listProductAttributes)}" >
											<c:set var="tam" value="${listComposition.size()}"/>
											<c:set var="nRow" value="${tam / tempValueQuantityRadio}"/>
											<c:set var="e" value="${tempValueQuantityRadio}"/>
											<c:set var="s" value="0"/>
											<c:forEach var="row" begin="0" end="${nRow-1}">
									     		<c:set var="textValue" value="${listComposition[s].name}||"/>
									     		<tr class='tr_decorado'> <td id='nameCompTD_${row}' class='td_decorado'>${listComposition[s].name}</td>
													<c:set var="j" value="0"/>
													<c:forEach var="i" begin="${s}" end="${e-1}">
														<c:set var="valueTemp" value="${listComposition[i].typeCompositionId.typeCompositionId}&&${listComposition[i].quantity}"/>
														<c:if test="${listComposition[i].checkHealth != null}" >
															<c:set var="valueTemp" value="${valueTemp}&&${listComposition[i].checkHealth}"/>
														</c:if>
														<td id='quantityValueTD_${row}_0' class='td_decorado'>${listComposition[i].quantity}</td>
														<td id='chechHealtValueTD_${row}_0' class='td_decorado'>${listComposition[i].checkHealth}</td>
														<c:choose>
															<c:when test="${j == 0}">
																<c:set var="textValue" value="${textValue}${valueTemp}"/>
															</c:when>
															<c:otherwise>
																<c:set var="textValue" value="${textValue}|**|${valueTemp}"/>
															</c:otherwise>
														</c:choose>
														<c:set var="j" value="${j+1}"/>
													</c:forEach>
													<td class='td_decorado' style='text-align: right'><div class='botonEditar test'><a href='javascript:editComposition("${row}")' title='Pulsa aqu&iacute; para Editar'></a></div></td>
											        <td class='td_decorado' style='text-align: right'><div class='botonEliminar'><a href='#' class='deleteRowCarga' title='Pulsa aqu&iacute; para Eliminar'></a></div></td>
											        <input type='hidden' name='compositionsValues' id='compositionValue_${row}' value='${textValue}' />
												</tr>
												<c:set var="s" value="${e}"/>
												<c:set var="e" value="${s+tempValueQuantityRadio}"/>
												<script type="text/javascript">
									     			indexRow++;
									     		</script>
											</c:forEach>
							     		</c:if>								     		
							    	</tbody>
								</table>
   	                    	</div>
 
							<div style="clear:both;">
								<label class="form_align43"><fmt:message key="form.remarkComposition"/>:</label>
								<form:input path="remarkComposition" id="remarkComposition" class="form_input_align" placeholder="texto"/>
							</div>
							<br/><br/><br/>
							
							<div style="clear:both;">
								<label class="form_align43"><fmt:message key="form.attributes"/>:</label>
								&nbsp;&nbsp;<input type="button" id="buttonAddProductAttri" class="boton" value="<fmt:message key="button.add"/> <fmt:message key="title.attribute"/>" title='<fmt:message key="onclick.New"/> <fmt:message key="title.attribute"/>.'/>
								<label class="error">*</label>
							</div>
							<div style="clear:both;">							
   	                    		<label class="form_align43"></label>
   	                    		<div id="requiredproductAttribute" class="form_input_align noDisplay requeredDataTable" >Debe seleccionar al menos un atributo de Producto <br/></div>
				             	<table id="productAttributeTable" class="tabla_decorado">
							    	<thead>
							    		<c:if test="${(not empty listProductAttributes)}" >
								     	<tr>
											<th class='th_decoradoRowspan'><fmt:message key='table.order'/></th>
											<th class='th_decoradoRowspan'><fmt:message key='table.name'/></th>
											<th class='th_decoradoRowspan'><fmt:message key='table.description'/></th>
											<th class='th_decoradoRowspan' colspan='2'><fmt:message key='table.actions'/></th>
										</tr>
										</c:if>
							     	</thead>				
							     	<tbody>
							     		<c:if test="${(not empty listProductAttributes)}" >
										<c:set var="j" value="1"/>
							     		<c:set var="i" value="0"/>
										<c:forEach items="${listProductAttributes}" var="item">
											<c:set var="valueTemp" value="${item.productattribute.name}&&${item.productattribute.detail}&&${item.productattribute.order}"/>
								     		<tr class='tr_decorado'>
												<td class='td_decorado' id='orderTD${i}'>${item.productattribute.order}</td>
												<td class='td_decorado' id='nameTD${i}'>${item.productattribute.name}</td>
												<td class='td_decorado' id='detailTD${i}'>${item.productattribute.detail}</td>
												<td class='td_decorado' style='text-align: right'><div class='botonEditar test'><a href='javascript:editProductAttribute("${i}")' title='Pulsa aqu&iacute; para Editar'></a></div></td>
						        				<td class='td_decorado' style='text-align: right'><div class='botonEliminar'><a href='#' class='deleteRowCarga' title='Pulsa aqu&iacute; para Eliminar'></a></div></td>
						        				<input type='hidden' name='productAttributeValues' id='productAttributeValues_${i}' value='${valueTemp}' />
											</tr>
	                            			<c:set var="i" value="${i+j}"/>
	                            			<script type="text/javascript">
								     			indexRow++;
								     		</script>
										</c:forEach> 
										</c:if>  
							    	</tbody>
								</table>
   	                    	</div>
							
   	                    	</br>
							<div style="clear:both;">
								<c:set var="showPresentation" scope="page"><fmt:message key="show.form.presentation"/>.</c:set>		
								<label class="form_align43"><fmt:message key="form.presentation"/>:</label>
								<form:input path="presentation" id="presentation" class="required form_input_align" title="${showPresentation}" placeholder="texto"/>
								<label class="error"><form:errors path="presentation" cssClass="error"></form:errors>*</label>
							</div>
							
							<div style="clear:both;">
								<label class="form_align43"><fmt:message key="form.codeBar"/>:</label>
								<form:input path="codeBar" id="codeBar" class="form_input_align numberOnlyNumber" placeholder="números"/>
							</div>
							
							<div style="clear: both">
								<label class="form_align43">&nbsp;</label>
								<table border="0" style="float: left">
									<fmt:message key="button.register" var="varSubmit" />
									<tr>
										<td style="text-align:right"><br/><input type="button" value="${varSubmit}" name="action"  class="boton buttonSave" title="<fmt:message key="onclick.for"/> ${varSubmit}" />&nbsp;&nbsp;</td>
										<td><br/>&nbsp;&nbsp;<input type="button" value="<fmt:message key="button.cancel"/>" name="action" onclick="mainProducts()" class="boton" title="<fmt:message key="onclick.cancel"/>"/></td>
									</tr>
								</table>
							</div>
						</form:form>												
					</div>	                               
                </div>
            </div><!--end of leftPan-->
            
            <div class="yDer" style="border: 1px solid #ccc;">
                  <%@include file="../../../notices.jsp" %>                       
            </div><!--end of rightPan-->
        </div><!--end main content -->
	</div>
</div>
</body>
</html>
